#include "./gis-model.h"

Point *createPoint(double x, double y)
{
	Point *point = (Point *)malloc(sizeof(Point));
	point->x = x;
	point->y = y;
	return point;
}

Vector *createVector(double x, double y)
{
	Vector *vector = (Vector *)malloc(sizeof(Vector));
	vector->x = x;
	vector->y = y;
	return vector;
}

Vector *createVectorByTwoPoint(Point *p1, Point *p2)
{
	Vector *vector = (Vector *)malloc(sizeof(Vector));
	vector->x = p2->x - p1->x;
	vector->y = p2->y - p1->y;
	return vector;
}

Vector *createVectorByLine(Line *line)
{
	Vector *vector = (Vector *)malloc(sizeof(Vector));
	vector->x = line->endX - line->startX;
	vector->y = line->endY - line->startY;
	return vector;
}

double vectorPointProduct(Vector *v1, Vector *v2)
{
	// 点乘：x1 * x2 + y1 * y2
	return v1->x * v2->x + v1->y * v2->y;
}

double vectorCrossProduct(Vector *v1, Vector *v2)
{
	// 叉乘：x1 * y2 - x2 * y1
	return v1->x * v2->y - v2->x * v1->y;
}

double vectorLength(Vector *vector)
{
	return sqrt(pow(vector->x, 2) + pow(vector->y, 2));
}

double vectorAngle(Vector *v1, Vector *v2)
{
	// 点乘公式：v1·v2 = |v1||v2|cosθ，根据此求出夹角
	double pointProduct = vectorPointProduct(v1, v2);
	double cosValue = pointProduct / (vectorLength(v1) * vectorLength(v2));
	// 反三角函数得到弧度制角度
	double angleArc = acos(cosValue);
	// 弧度制转角度制
	double angle = angleArc / M_PI * 180;
	return fabs(angle);
}

Line *createLine(double startX, double startY, double endX, double endY)
{
	Line *line = (Line *)malloc(sizeof(Line));
	line->startX = startX;
	line->startY = startY;
	line->endX = endX;
	line->endY = endY;
	return line;
}

double lineLength(Line *line)
{
	return sqrt(pow(line->endX - line->startX, 2) + pow(line->endY - line->startY, 2));
}

Polygon *createPolygon(Point points[], int n)
{
	Polygon *polygon = (Polygon *)malloc(sizeof(Polygon));
	polygon->points = (Point *)calloc(n, sizeof(Point));
	polygon->pointCount = n;
	int i;
	for (i = 0; i < n; i++)
	{
		polygon->points[i] = points[i];
	}
	return polygon;
}

Circle *createCircle(double x, double y, double r)
{
	Circle *circle = (Circle *)malloc(sizeof(Circle));
	circle->center = createPoint(x, y);
	circle->radius = r;
	return circle;
}

Rectangle *createRectangle(double upLeftX, double upLeftY, double bottomRightX, double bottomRightY)
{
	Rectangle *rectangle = (Rectangle *)malloc(sizeof(Rectangle));
	rectangle->upLeft = createPoint(upLeftX, upLeftY);
	rectangle->bottomRight = createPoint(bottomRightX, bottomRightY);
	return rectangle;
}